package com.ujiuye.Servlet;

import com.ujiuye.Dao.ProductDao;
import com.ujiuye.entity.Product;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/ProductServlet")
public class ProducServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          request.setCharacterEncoding("utf-8");
          response.setContentType("text/html;charset=utf-8");
          String flag=request.getParameter("flag");
        ProductDao pd=new ProductDao();
        if ("getAllProducts".equals(flag)){
            List<Product> list = pd.select();
            System.out.println(list);
            request.setAttribute("prolist",list);
            request.getRequestDispatcher("product.jsp").forward(request,response);
        }else if ("addTrolley".equals(flag)){
            int pid=Integer.parseInt(request.getParameter("pid"));
            Product pro = pd.getProductByPid(pid);
            HttpSession session=request.getSession();
            //设置session的时效为7天
            session.setMaxInactiveInterval(60*60*24*7);
            Cookie cookie=new Cookie("JSESSIONID",session.getId());
            cookie.setMaxAge(60*60*24*7);
            response.addCookie(cookie);
            //从session中获取存放商品的集合
            List<Product> list=(List<Product>) session.getAttribute("trolley");
            //如果购物车中没有商品，那么session中就没有集合，取到的就是null
            if (list==null){
                list=new ArrayList<>();
            }
            //将商品放到取出的集合中
            list.add(pro);
            //再将集合放回session中
            session.setAttribute("trolley",list);
            //跳转到购物车页面
            response.sendRedirect("trolley.jsp");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
